<?php

namespace app\services;

use Exception;
use plugin\admin\app\model\User;
use plugin\admin\app\model\Work;
use plugin\admin\app\model\WorkShare;

class WorkShareService
{
    public static function getShareData($work_id = 0)
    {
        try {
            $user_id = get_user_id();
            $workShare = WorkShare::where('user_id', $user_id)->where('work_id', $work_id)->first();

            return $workShare;

        } catch (Exception $e) {
            throw new Exception('获取分享数据失败: ' . $e->getMessage());
        }
    }

    public static function generateShareLink($invite_code_generate_way = 0, $invite_code = '', $expiry_time = 7, $auto_fill = false, $work_id = 0)
    {
        try {
            // 生成唯一编号
            $no = uniqid();

            // 获取用户 ID
            $user_id = get_user_id();

            // 生成邀请码
            if ($invite_code_generate_way == 0) {
                $invite_code = self::generateInviteCode(5);
            }

            if (!Work::where('user_id', $user_id)->where('id', $work_id)->first()) {
                throw new \Exception('作品不存在');
            }

            // 计算过期时间戳
            if ($expiry_time <= 0) {
                $expiry_timestamp = -1;
                $expiry_day = -1;
            } else {
                $expiry_timestamp = strtotime("+{$expiry_time} days");
                $expiry_day = $expiry_time;
            }

            // 当前创建时间
            $create_time = date('Y-m-d H:i:s');

            // 查询是否已存在记录
            $existingShare = WorkShare::where('user_id', $user_id)->where('work_id', $work_id)->first();

            if ($existingShare) {
                $existingShare->no = $no;
                $existingShare->invite_code = $invite_code;
                $existingShare->expiry_time = $expiry_timestamp;
                $existingShare->expiry_day = $expiry_day;
                $existingShare->auto_fill = $auto_fill ? 1 : 0;
                $existingShare->invite_code_generate_way = $invite_code_generate_way;
                $existingShare->save();
            } else {
                // 如果记录不存在，插入新记录
                $data = [
                    'no' => $no,
                    'user_id' => $user_id,
                    'work_id' => $work_id,
                    'invite_code' => $invite_code,
                    'invite_code_generate_way' => $invite_code_generate_way,
                    'expiry_time' => $expiry_timestamp,
                    'create_time' => $create_time,
                    'expiry_day' => $expiry_day,
                    'auto_fill' => $auto_fill ? 1 : 0,
                ];

                WorkShare::insert($data);
            }

            $agent = request()->header('Agent');

            if ($agent == 'web') {
                return getenv('PC_URL') . '/share?no=' . $no . ($auto_fill == 1 ? '&invite_code=' . $invite_code : '');
            } else {
                return getenv('H5_URL') . '/share?no=' . $no . ($auto_fill == 1 ? '&invite_code=' . $invite_code : '');
            }


        } catch (Exception $e) {
            throw new Exception('生成分享链接失败: ' . $e->getMessage());
        }
    }

    public static function checkUrl($no, $invite_code = '')
    {
        try {
            $workShare = WorkShare::where('no', $no)->first();
            if (!$workShare) {
                throw new Exception('分享链接不存在');
            }

            // 检查是否过期
            if ($workShare->expiry_time > 0 && $workShare->expiry_time < time()) {
                throw new Exception('分享链接已过期');
            }

            if ($workShare->invite_code != $invite_code) {
                throw new Exception('邀请码不正确');
            }

            $work = Work::where('id', $workShare->work_id)->first();
            $user = UserService::profile($workShare->user_id);

            return [
                'url' => getenv('TOOLS_URL') . '?command=preview&work_id=' . $work['id'],
                'nickname' => $user['nickname'],
            ];

        } catch (Exception $e) {
            throw new Exception('检查分享链接失败: ' . $e->getMessage());
        }
    }

    private static function generateInviteCode($length = 5)
    {
        $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $invite_code = '';
        for ($i = 0; $i < $length; $i++) {
            $invite_code .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $invite_code;
    }
}